package org.his.controller;

import java.util.Map;

import org.his.entity.Doctor;
import org.his.entity.Login;
import org.his.service.DoctorService;
import org.his.service.LoginService;
import org.his.service.impl.LoginServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;


@SessionAttributes(value = { "login","doctor" })

@Controller
@RequestMapping("/login")
public class LoginController {
	@Autowired
	private LoginService loginService;
	@Autowired
	private DoctorService doctorService;
	
	@RequestMapping("query/{username}")
	public String query(@PathVariable("username") String username,Map<String,Object> map) {
		Login user = loginService.queryLoginInfoByusername(username);
		map.put("user", user);
		return "result";
	}
	@RequestMapping(value = "/logout",method = RequestMethod.GET)
	@ResponseBody
	public String logout(SessionStatus status) {
		status.setComplete();
		return "{\"success\":\"true\",\"message\":\"注销成功\"}";
	}
	
	
	@RequestMapping(value = "/check", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String login(Login user, ModelMap model) {
		// 后台登录验证
		
		Login logininfo = loginService.queryLoginInfo(user);
		if (logininfo != null && logininfo.getUsername() != null) {
			// 验证通过后，再判断是否已为该管理员分配功能权限
			if (logininfo.getPrivilege()==3) {
				// 验证通过且已分配功能权限，则将logininfo对象存入model中
				model.put("login", logininfo);
				// 以JSON格式向页面发送成功信息
				return "{\"success\":\"true3\",\"message\":\"登录成功\"}";
			}else if (logininfo.getPrivilege()==2) {
				Doctor doctorinfo = doctorService.queryDoctorByNo(logininfo.getUsername());
				model.put("doctor", doctorinfo);
				model.put("login", logininfo);
				return "{\"success\":\"true2\",\"message\":\"登录成功\"}";
			}else if (logininfo.getPrivilege()==1) {
				model.put("login", logininfo);
				return "{\"success\":\"true1\",\"message\":\"登录成功\"}";
			}else {
				return "{\"success\":\"false\",\"message\":\"您没有权限，请联系超级管理员设置权限！\"}";
			}
		} else
			return "{\"success\":\"false\",\"message\":\"登录失败\"}";
	}
}
